package com.wang.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wang.conf.AppConf;
import com.wang.wxpojo.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author wcy
 * @date 2023-02-10 17:57
 */
public class WxMsgUtil {


    static  RestTemplate restTemplate = getRestTemplate();


    public static RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(simpleClientHttpRequestFactory());
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    public static ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(30000);//restTemplate 请求超时时间
        factory.setConnectTimeout(30000);// 连接超时
        return factory;
    }

   /* static String token = "";
    static String[] to_openid_list = {"onVjS4i4kSclRe-vj1MRI8gxXm4U"};  //测试使用
    static String mp_template_id = AppConf.template_id;
    static String sn = AppConf.sn;
    static String modelId = AppConf.modelId;
    static String page = AppConf.page;*/


   /* public static void main(String[] args) {
        System.out.println(getToken());
    }*/
    public static void main(String[] args) {



        WxMsgPack2 wxMsgPack = new WxMsgPack2();
        //wxMsgPack.setAccessToken(access_token);
        wxMsgPack.setTouser("owzGn4uUl0KLYq4yJsTmQKRnye-c");

        MpTemplateMsg2 mpTemplateMsg = new MpTemplateMsg2();
        mpTemplateMsg.setAppid(AppConf.mpAppId);
        mpTemplateMsg.setTemplate_id(AppConf.mpTemplate_id);
        mpTemplateMsg.setUrl(AppConf.weAppUrl);





      /*  WxDataPack wxDataPack = new WxDataPack();
        wxDataPack.setFirst(new MpFirst("您好:"+"陆恒大酒店1"+"监测数据异常","#173177"));
        //wxDataPack.setProjectName(new MpProjectName("pH;ORP","#173177"));
        wxDataPack.setTime(new MpTime("2023-02-12 11:40:20"));
        wxDataPack.setAddress(new MpAddress("杭州市上城区","#FF0000"));
        wxDataPack.setResult(new MpResult("pH:8.3,偏高;"+"ORP:670,偏高","#173177"));
        wxDataPack.setRemark(new MpRemark("如查看详细数据，点击进入小程序查看，如有疑问，请联系客服"));*/


        WxDataPack2 wxDataPack = new WxDataPack2();
        wxDataPack.setFirst(new MpFirst("您好:"+"陆恒大酒店1"+"监测数据异常"));
        wxDataPack.setKeyword1(new KeyWord1("陆恒大酒店1","#FF0000"));
        wxDataPack.setKeyword2(new KeyWord1("2022-10-20 10:20:30","#FF0000"));
        wxDataPack.setKeyword3(new KeyWord1("lhtest-dz451000","#FF0000"));
        wxDataPack.setKeyword4(new KeyWord1("pH:8.5;偏高","#FF0000"));
        wxDataPack.setRemark(new MpRemark("测试"));

        mpTemplateMsg.setData(wxDataPack);


        MiniProgram miniProgram = new MiniProgram();
        miniProgram.setAppid(AppConf.weAppId);
        miniProgram.setPagepath(AppConf.weAppPagePath);

        mpTemplateMsg.setMiniprogram(miniProgram);

        wxMsgPack.setMp_template_msg(mpTemplateMsg);

        System.out.println(JSON.toJSON(wxMsgPack).toString());
        sendWxData(JSON.toJSONString(wxMsgPack));


    }

/*
    public static void main(String[] args) {

        String wxData = "{\"mp_0000008b5a4c7b3513da7d\",\"data\":{\"address\":{\"value\":\"未设置地址\"},\"first\":{\"value\":\"您好:LH-DZ_test69211监测数据异常\"},\"projectName\":{\"color\":\"#173177\",\"value\":\"氨氮;\"},\"remark\":{\"value\":\"如查看详细数据，点击进入小程序查看，如有疑问，请联系客服\"},\"result\":{\"color\":\"#FF0000\",\"value\":\"氨氮:0.40,偏低\\n\\n\"},\"time\":{\"value\":\"2023-05-12 15:43:35\"}},\"miniprogram\":{\"appid\":\"wxbc5ccf8ddfeaf689\",\"pagepath\":\"pages/home/index\"},\"template_id\":\"M5BgZ92EjqQVxcUK8Rx_Xo2ivVVl_kFjxgN6vdJVzEU\",\"url\":\"http://weixin.qq.com/download\"},\"touser\":\"owzGn4uUl0KLYq4yJsTmQKRnye-c\"}";
        sendWxData(wxData);
    }
    */



    //发送微信公众号通知
    public static  String  sendWxData(String wxData){
        String access_token = getMyAppToken();

        System.out.println(access_token);
        String sendDataUrl = AppConf.mp_sendDataUrl+access_token;
        String result =  restTemplate.postForObject(sendDataUrl,wxData,String.class);


        JSONObject jsonObject =  JSON.parseObject(result,JSONObject.class);
        System.out.println(jsonObject.toString());
        String resultCode = jsonObject.get("errcode").toString();
        if(resultCode.equals("0")){
            return "success";

        }else {
            return "error";
        }

    }


    public static String  getMyAppToken(){

        Long nowTime = new Date().getTime();


        if(EmptyUtil.isNotNull(AppConf.access_token) && (nowTime-AppConf.getAccess_tokenTime)<7100){

            return AppConf.access_token;
        }else {
            AppConf.access_token = getToken();
            AppConf.getAccess_tokenTime = new Date().getTime();
            return AppConf.access_token;
        }
    }


    public static String getToken() {

        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+AppConf.weAppId+"&secret="+AppConf.weAppSecret;

        ResponseEntity<String> forEntity = restTemplate.getForEntity(tokenUrl, String.class, new Object[0]);
        String body = (String)forEntity.getBody();

        JSONObject jsonObject1 = JSON.parseObject(body,JSONObject.class);


        return jsonObject1.get("access_token").toString();

    }

}
